package com.nettytime.util.testjiebaonianbaos;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class FixedLengthMessageEncoder extends MessageToByteEncoder<String> {
    private int length;

    public FixedLengthMessageEncoder(int length) {
        this.length = length;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, ByteBuf out)
            throws Exception {
        // 对于超过指定长度的消息，这里直接抛出异常
        if (msg.length() > length) {
            throw new UnsupportedOperationException("字符串长度超出长度了，指定长度为:"+length);
        }
        // 如果长度不足，则进行补全
        if (msg.length() < length) {
            msg = addSpace(msg);
        }
        //Unpooled.wrappedBuffer实现零拷贝，将字符串转为ByteBuf
        ctx.writeAndFlush(Unpooled.wrappedBuffer(msg.getBytes()));
    }

    // 如果没有达到指定长度进行空格补全
    private String addSpace(String msg) {
        StringBuilder builder = new StringBuilder(msg);
        for (int i = 0; i < length - msg.length(); i++) {
            builder.append(" ");
        }

        return builder.toString();
    }
}
